/**
 * 全局变量
 */
var selectUserId = '';
var lastIndex = 'lastIndex';
$(function () {
    /*
    * 加载列表数据
    * */
    $('#listGrid').datagrid({
        url: ROOT_PATH + '/risk/recognise/queryListByParam.shtml',
        queryParams: {
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        sortOrder: true,
        striped: true,
        fit: true,
        view: detailview,
        detailFormatter: function (index, row) {  //返回一个空的div，展开行的时候将展开内容放到这个div中
            return '<div class="taskddv" style="padding:5px;border-left: solid 1.5px #DCDCDC;"></div>';
        },
        onCollapseRow: function (index, row) {
            var ddv = $('#listGrid').datagrid('getRowDetail', index).find('table.tbddv');
            ddv.datagrid('clearSelections');
        },
        onExpandRow: function (index, row) {
            $('.taskddv').html('');
            if (lastIndex != 'lastIndex' && lastIndex != index) {
                $('#listGrid').datagrid('collapseRow', lastIndex);
                $('.taskddv').empty();
            }
            var htmlTb = '<table id="taskDivTb" class="tbddv"></table>';
            $('.taskddv').append(htmlTb);
            var ddv = $('#listGrid').datagrid('getRowDetail', index).find('table.tbddv');
            var tableField = eval(row.methodTypeFlag + "_Field").concat(base_Field);
            ddv.datagrid({
                url: ROOT_PATH + '/risk/recognise/queryRecogniseDetailList.shtml',
                queryParams: {
                    recogniseId: row.id,
                },
                fitColumns: true,
                singleSelect: true,
                rownumbers: true,
                height: 'auto',
                columns: [tableField],
                onLoadSuccess: function () {
                    lastIndex = index;
                    $('#listGrid').datagrid('fixDetailRowHeight', index);
                },

            });
            $('#listGrid').datagrid('fixDetailRowHeight', index);
        },
        columns: [[
            {field: 'id', width: 10, checkbox: true},
            {
                field: 'type', title: '识别对象类型', width: 10,
                formatter: function (value, row, index) {
                    if (value === 0) {
                        return "<a href='javascript:void(0)' style='color: deepskyblue;' onclick='openDetailPage(\"" + row.id + "\")'>设备设施</a>";
                    } else if (value === 1) {
                        return "<a href='javascript:void(0)' style='color: deepskyblue;' onclick='openDetailPage(\"" + row.id + "\")'>作业活动</a>";
                    } else {
                        return '';
                    }
                }
            },
            {
                field: 'jobContent', title: '风险点/作业活动', width: 10,
                formatter: function (value, row, index) {
                    if (row.type === 0) {
                        return row.regionPointName;
                    } else if (row.type === 1) {
                        return row.jobContent;
                    } else {
                        return '';
                    }
                }
            },
            {field: 'deptName', title: '识别单位', width: 10},
            {field: 'regionName', title: '风险区域', width: 10},
            {field: 'riskNum', title: '风险数量', width: 10},
            {field: 'userNames', title: '评价人员', width: 10},
            {field: 'methodTypeName', title: '评价方法', width: 10},
            {field: 'recogniseDate', title: '评价时间', width: 10},
            {
                field: 'appState', title: '状态', width: 10, sortable: true,
                formatter: function (value, row, index) {
                    if (value === "" || value === null || value === undefined) {
                        return "<span>未审批</span>";
                    } else {
                        if (value == -1) {
                            return "<span style='color: #FF0000;'>审批未通过</span>";
                        } else if (value == 1) {
                            return "<a href='javascript:void(0);' onclick=\"flowMonitorByBusinessId('" + row.id + "')\" style='color: #0abffc;'>审批通过</a>";
                        } else {
                            return "<a href='javascript:void(0);' onclick=\"flowMonitorByBusinessId('" + row.id + "')\" style='color: #FF8C00'>正在审批</a>"
                        }
                    }
                }
            },
            {field: 'addUserName', title: '登记人员', width: 10},
            {field: 'addDeptName', title: '登记部门', width: 10},
            {field: 'addTime', title: '登记时间', width: 10},
            {field: 'remarks', title: '备注', width: 10}
        ]],
        toolbar: '#toolbar'
    });
    /**
     * 加载下拉列表信息
     *
     */
    queryRegionList();//风险区域
    queryDepartmentTree();//部门下拉列表
    //加载评价方法
    queryMethodTypeList("search_methodTypeId", CONSTANT.DictionaryTypeDefConstants.RISK_RECOGNISE_MOTHOD);//评价方法
    $("#search_recogniseUser").textbox({
        iconWidth: 22,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                selectUserId = "search_recogniseUser";
                add_contractorInfo_func();
            }
        },
            {
                iconCls: 'icon-remove',
                handler: function (e) {
                    $(e.data.target).textbox('clear');

                }
            }
        ]
    });
    //绑定人员选择按钮事件
    $("#searchAddUser").textbox({
        iconWidth: 22,
        icons: [
            {
                iconCls: 'icon-add',
                handler: function (e) {
                    selectUserId = "searchAddUser";
                    add_contractorInfo_func();
                }
            },
            {
                iconCls: 'icon-remove',
                handler: function (e) {
                    $(e.data.target).textbox('clear');

                }
            }
        ]
    });
    //绑定按钮事件
    $('#btn_advanced_search').on("click", function () {
        $('#searchForm2').toggle();
        $('#listGrid').datagrid('resize');
    });
    $("#btn_risk_recognise_add").on("click", function () {
        addRecognise();
    });
    $("#btn_risk_recognise_edit").on("click", function () {
        editRecognise();
    });
    $("#btn_risk_recognise_delete").on("click", function () {
        deleteRecognise();
    });
    $("#btn_risk_recognise_submit").on("click", function () {
        submitRecognise();
    });

    //查询按钮绑定事件
    $("#btn_search").on('click', function () {
        searchFun();
    });
    $('#btn_clear').on('click', function () {
        $('#searchForm1').form('clear');
        $('#searchForm2').form('clear');
    });

});

/**
 * 打开风险识别评价新增页面
 */
function addRecognise() {
    WindowManager.openLayer({
        type: 2,
        title: '新增风险风险识别评价信息',
        area: ['1200px', '90%'],
        content: ROOT_PATH + '/risk/recognise/add.shtml',
        callBack: function (data) {//窗口关闭后的回调函数
            $('#listGrid').datagrid("reload");
        }
    });
}

/**
 * 打开风险可能性等级编辑页面
 */
function editRecognise() {
    var selectedRow = $('#listGrid').datagrid('getSelected');
    //alert();
    if (!(selectedRow.appState == undefined)) {
        layer.msg("不可编辑！", {time: 1000, icon: 1}, function () {
        });
        return false;
    }
    if (selectedRow) {
        var businessId = selectedRow.id;
        WindowManager.openLayer({
            type: 2,
            title: '编辑风险识别评价信息',
            area: ['1200px', '90%'],
            content: ROOT_PATH + '/risk/recognise/edit.shtml?businessId=' + businessId,
            callBack: function (data) {
                $('#listGrid').datagrid("reload");
            }
        });
    } else {
        layer.alert("请选择数据！");
    }

}

/**
 * 删除风险等级信息
 */
function deleteRecognise() {
    var selectedRow = $('#listGrid').datagrid('getSelected');
    if (!(selectedRow.appState == undefined)) {
        layer.msg("不可删除！", {time: 1000, icon: 1}, function () {
        });
        return false;
    }
    if (selectedRow) {
        var businessId = selectedRow.id;
        var index = layer.confirm("确定删除改行数据吗？", {btn: ["确定", "取消"]}, function () {
            $.ajax({
                type: 'post',
                url: ROOT_PATH + '/risk/recognise/deleteRecogniseInfo.shtml?businessId=' + businessId,
                dataType: "json",
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.message, {time: 1000, icon: 1}, function () {
                            $('#listGrid').datagrid('reload');
                        });
                    } else {
                        layer.msg(result.message, {time: 1000, icon: 1}, function () {
                        });
                    }
                }
            });
        })
    } else {
        layer.alert("请选择数据！");
    }
}

/**
 * 打开详情页面
 */
function openDetailPage(businessId) {
    WindowManager.openLayer({
        type: 2,
        title: '风险识别评价信息',
        area: ['1200px', '90%'],
        content: ROOT_PATH + '/risk/recognise/detail.shtml?businessId=' + businessId,
        callBack: function (data) {
            $('#listGrid').datagrid("reload");
        }
    });
}

/**
 * 查询按钮方法
 */
function searchFun() {
    var search1 = $('#searchForm1').serializeJson();
    var search2 = $('#searchForm2').serializeJson();
    var search = $.extend(search1, search2);
    //排序参数
    search.sort = "addTime";
    search.order = 'desc';
    $('#listGrid').datagrid('load', search);
}

/**
 * 查询风险区域列表
 */
function queryRegionList() {
    $.ajax({
        url: ROOT_PATH + '/risk/region/queryComboboxList.shtml',//提交地址
        data: {},
        type: "POST",
        dataType: "json",
        success: function (result) {
            $('#search_regionId').combobox(
                {
                    data: result,
                    valueField: 'id',
                    textField: 'text',
                    //limitToList:'true',
                    /*loadFilter:function(data){
                     var newData = new Array();
                     newData.push({id:"",text:'请选择'});
                     for(var i=0;i<data.length;i++){
                     newData.push(data[i])
                     }
                     return newData;
                     },*/
                    //hasDownArrow:false,//隐藏倒三角
                }
            );

        }
    });
}


/**
 * 查询部门树方法
 */
function queryDepartmentTree() {
    $.ajax({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data: {parentId: 0},//将表单数据序列化
        type: "POST",
        dataType: "json",
        success: function (result) {
            //隐患所在部门
            $('#searchDept').combotree(
                {
                    data: result,
                    loadFilter: function (data) {
                        var newData = new Array();
                        newData.push({id: "", text: '请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );
            //隐患登记部门
            $('#searchAddDept').combotree(
                {
                    data: result,
                    loadFilter: function (data) {
                        var newData = new Array();
                        newData.push({id: "", text: '请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );

        }
    });
}

/**
 * 人员信息选择
 */
var add_contractorInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {//窗口关闭后的回调函数
            if (selectUserId == "" || selectUserId == null) {
                var dutyUserED = datagrid.datagrid('getEditor', {index: editRow, field: 'dutyUserName'});
                var dutyUserIdED = datagrid.datagrid('getEditor', {index: editRow, field: 'dutyUserId'});
                $(dutyUserED.target).textbox("setValue", data[0].name)
                $(dutyUserIdED.target).textbox("setValue", data[0].id)
            } else {//给正常文本框赋值
                $("#" + selectUserId).textbox('setValue', data[0].id);
                $("#" + selectUserId).textbox('setText', data[0].name);
                selectUserId = "";
            }
        }
    });
};

/**
 * 查询评价方法数据字典
 * @param id
 * @param code
 */
function queryMethodTypeList(id, code) {
    $.ajax({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',//提交地址
        data: {code: code},//将表单数据序列化
        type: "POST",
        dataType: "json",
        success: function (result) {
            /* var data = [];
             for(i=0;i<result.length;i++){
                 if(result[i].data1 == recogniseType || result[i].data1== 2){
                     data.push(result[i]);
                 }
             }*/
            $('#' + id).combobox(
                {
                    data: result,
                    valueField: 'id',
                    textField: 'text',
                    loadFilter: function (data) {
                        var newData = new Array();
                        newData.push({id: "", text: '请选择'});
                        for (var i = 0; i < data.length; i++) {
                            newData.push(data[i])
                        }
                        return newData;
                    }
                    /*,
                    onChange:function(newVal,oldVal){
                        if(datagrid){
                            if($("#detailForm").form("validate")){
                                saveTableRow();
                            }else{
                                datagrid.datagrid('deleteRow', editRow);
                                editRow=undefined;
                            }
                        }
                        if(newVal){
                            //$("#detailListDiv").children().show();
                            for(i=0;i<data.length;i++){
                                if(data[i].id==newVal){
                                    var tableField = eval(data[i].data2+"_Field").concat(base_Field);
                                    tableOptions.columns = [tableField];
                                    datagrid = $("#detailList").datagrid(tableOptions);
                                }
                            }
                        }else{
                            $("#detailListDiv").children().hide();
                        }

                    }*/
                }
            );

        }
    });
}

/**
 * 提交审批的方法
 * @returns {boolean}
 */
function submitRecognise() {
    var $selected = $('#listGrid').datagrid('getSelections');
    if ($selected.length != 1) {
        layer.alert('请选择一条数据！');
        return false;
    }
    var businessId = $selected[0].id;//请假单id
    if (!($selected[0].appState === null || $selected[0].appState === "" || $selected[0].appState === undefined)) {
        layer.alert('业务流程已存在，禁止重复提交！');
        return false;
    }
    var layerIndex = layer.confirm('是否确定提交审批？', function () {
        layer.close(layerIndex);
        /***
         * 选择处理人
         */
        WindowManager.openLayer({
            type: 2,
            title: '选择下一环节处理人',
            area: ['370px', '180px'],
            content: ROOT_PATH + '/workflow/flowManagement/toFlowNextUserSelectPage.shtml',
            data: {id: 'ff', name: '我是名称'},
            callBack: function (data) {//窗口关闭后的回调函数
                //得到选择的人员
                if (data == null || data === "") {
                    layer.alert("请选择处理人!");
                    return false;
                }
                $.ajax({
                    type: "POST",
                    url: ROOT_PATH + '/risk/recognise/submitApplication.shtml',
                    data: {id: $selected[0].id, nextUserId: data},
                    success: function (result) {
                        result = $.parseJSON(result);
                        if (result.success) {
                            layer.msg(result.message, {time: 1000, icon: 1}, function () {
                                $('#listGrid').datagrid('load');
                                layer.closeAll(); //先得到当前iframe层的索引
                            });
                        } else {
                            layer.msg(result.message);
                        }
                    }
                });
            }
        });

    });
}

/**
 * 定义不同方法的编辑表格字段
 */
var base_Field = [
    {field: 'danger', title: '危害', width: 300},
    {field: 'consequence', title: '主要后果', width: 300},
    {field: 'riskTypeName', width: 100, hidden: true, editor: {type: 'textbox'}},
    {
        field: 'riskTypeId', title: '风险类别', width: 300,
        formatter: function (value, row, index) {
            if (row.riskTypeName) {
                return row.riskTypeName;
            }
            return '';
        }
    },
    {
        field: 'riskGrade', title: '风险等级', width: 150,
        styler: function (value, row, index) {
            return "background-color:#" + row.riskGradeColor;
        }
    },
    {field: 'existMeasure', title: '现有控制措施及执行情况', width: 350},
    {field: 'adviseMeasure', title: '建议控制措施', width: 300}
];
var scl_Field = [    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'checkProject', title: '检查项目', width: 300},
    {field: 'checkStandard', title: '检查标准', width: 300}
];
var pha_Field = [
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'event', title: '事件', width: 300}];
var fmea_Field = [//{field:'id',width:100,checkbox:true},
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'analyzeProject', title: '分析项目', width: 300},
    {field: 'failureMode', title: '失效模式', width: 300}];
var eta_Field = [
    // {field:'id',width:100,checkbox:true},
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'analyzeStage', title: '分析阶段', width: 300},
    {field: 'safetyProtect', title: '安全防护', width: 300}

];
var fta_Field = [
    //{field:'id',width:100,checkbox:true},
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'analyzeProject', title: '分析项目', width: 300}
];
var hazop_Field = [
    //{field:'id',width:100,checkbox:true},
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'node', title: '节点', width: 300},
    {field: 'deviation', title: '偏差', width: 300}

];
var jha_Field = [
    //{field:'id',width:100,checkbox:true},
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'jobStep', title: '作业步骤', width: 300}
];
var jsa_Field = [
    //{field:'id',width:100,checkbox:true},
    //{field:'dutyUserId',width:100,hidden:true},
    {field: 'jobStep', title: '作业步骤', width: 300}
];